package org.smart4j.framework.helper;

import org.apache.commons.collections4.CollectionUtils;
import org.smart4j.framework.annotation.MappingAction;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.util.ArrayUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 * 控制器助手类
 *
 * @author: Mr.Zhou
 * @create: 2018-10-24 15:16
 **/
public final class ControllerHelper {

    /**
     * 用于存放请求与处理器的映射关系（简称 Action Map）
     */
    private static final Map<Request,Handler> ACTION_MAP=new HashMap<Request, Handler>();

    static {
        Set<Class<?>> controllerClassSet=ClassHelper.getControllerSet();
        if(CollectionUtils.isNotEmpty(controllerClassSet)){
            for(Class<?> controllerClass:controllerClassSet){
                Method[] methods=controllerClass.getDeclaredMethods();
                if(ArrayUtil.isNotEmpty(methods)){
                    for (Method method:methods){
                        if(method.isAnnotationPresent(MappingAction.class)){
                            MappingAction mappingAction=method.getAnnotation(MappingAction.class);
                            String path=mappingAction.value();
                            String methodStr=mappingAction.method();
                            Request request=new Request(methodStr,path);
                            Handler handler=new Handler(controllerClass,method);
                            ACTION_MAP.put(request,handler);
                        }
                    }

                }
            }

        }
    }

    /**
     * 获取 Handler
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request=new Request(requestMethod,requestPath);
        return ACTION_MAP.get(request);
    }

}
